<?php
require_once(dirname(__FILE__) ."/../settings.inc.php");
if(file_exists(X2_PROJECT ."/settings.inc.php")){
  require_once(X2_PROJECT ."/settings.inc.php");
}
require_once(X2 ."/functions.inc.php");

require_once(X2 ."/classes/x2.class.php");

$begin = getmicrotime();
$xingle = new x2();
if(!$xingle -> user -> isAuthorized()){
//  exit('<html><script type="text/javascript">window.close()</script></html>');
}
$xingle -> db -> debug = true;
$contentTypes = include(X2 . "/contentTypes.inc.php");
$tstamp = time();
$nodeInfo = array(
  'id' => 0,
  'parent' => isset($_GET['xingle:parent'])? intval($_GET['xingle:parent']) : 0,
  'position' => 0,
  'atime' => $tstamp,
  'ctime' => $tstamp,
  'alias' => '',
  'label' => null,
  'labels' => '',
  'defaultLang' => 1,
  'visible' => 0,
  'state' => 'published',
  'refId' => null,
  'templates' => '',
  'context' => '',
  'contentType' => 0,
  'dateStart' => null,
  'dateEnd' => null,
  'title' => '',
  'description' => '',
  'keywords' => '',
  'thumbnail' => '',
  'URL' => ''
);
$id = isset($_GET['xingle:id'])? intval($_GET['xingle:id']) : 0;
$action = isset($_GET['xingle:action'])? $_GET['xingle:action'] : "";

if($id != 0){
  $data = $xingle -> getNodeInfo($id);
  if($data !== false) $nodeInfo = $data;
  $labelsArray = $labels -> getDocLabels($id);
  $labelsList = array();
  foreach($labelsArray as $idNamePair)$labelsList[] = $idNamePair['id'];
  $nodeInfo['labels'] = join(",", $labelsList);
}
$langs = $xingle -> getLanguages();

switch ($action){
  case 'update':
  	header("Content-type: text/xml; charset=utf-8");

    if($xingle -> aliasExists($_REQUEST['parent'], $_REQUEST['alias'], $_REQUEST['id'])){
      exit(
        '<error description="Такой псевдоним в этом разделе уже существует. Выберите другой."/>'
      );
    }
    if(empty($_REQUEST['label'])) $_REQUEST['label'] = null;
    if(empty($_REQUEST['templates'])) $_REQUEST['templates'] = null;
    if(empty($_REQUEST['context'])) $_REQUEST['context'] = null;
    if(!@domxml_open_mem('<root>'.$_REQUEST['title'].'</root>')){
      $_REQUEST['title'] = htmlspecialchars(
        $_REQUEST['title'],
        ENT_NOQUOTES,
        "UTF-8"
      );
    }
    if(!@domxml_open_mem('<root>'.$_REQUEST['description'].'</root>')){
      $_REQUEST['description'] = htmlspecialchars(
        $_REQUEST['description'],
        ENT_NOQUOTES,
        "UTF-8"
      );
    }
    if(!@domxml_open_mem('<root>'.$_REQUEST['keywords'].'</root>')){
      $_REQUEST['keywords'] = htmlspecialchars(
        $_REQUEST['keywords'],
        ENT_NOQUOTES,
        "UTF-8"
      );
    }
    if($xingle -> updateNodeInfo($_REQUEST)){ // проверить!!!!!
      $labels -> setDocLabels(
        $_REQUEST['id'],
        explode(",", trim($_REQUEST['labels']))
      );
      $nodeData = $xingle -> getNodeInfo($_REQUEST['id']);
      $visible = (1 + $nodeData['visible'])/2;

      exit(
        '<div class="node" nodeId="'. $nodeData['id'] .'" label="'. $nodeData['label'] .'" unselectable="on"><div class="nodeHead" unselectable="on"><input type="button" class="nodeReverseEmpty" unselectable="on" onclick="switchNode(this.nextSibling)" onfocus="this.blur()" /><span class="nodeTitleNormal" id="t'. strtr($nodeData['URL'], '/', '.') .'" title="'. $nodeData['title']. '" unselectable="on" onclick="highlight(this)"><input type="button" class="nodeIconPage" style="-moz-opacity: '. $visible .'; opacity: '. $visible .'; filter:progid:DXImageTransform.Microsoft.Alpha(Opacity='. ($visible*100) .')" unselectable="on" onfocus="this.blur()" />&#xA0;'. $nodeData['title'] .'</span></div><div class="nodeChildren" style="display:none" unselectable="on"><!-- Дочерние узлы --></div></div>'
      );
    } else {
      exit(
        '<error description="Не удалось обновить информацию"/>'
      );
    }
  break;
  case 'create':
  	header("Content-type: text/xml; charset=utf-8");
//    exit('<error description="Dump"><![CDATA['.var_export($_REQUEST, true).']]><![CDATA['.var_export($HTTP_RAW_POST_DATA, true).']]></error>');
    if(empty($_REQUEST['label'])) $_REQUEST['label'] = null;
    if(empty($_REQUEST['templates'])) $_REQUEST['templates'] = null;
    if(empty($_REQUEST['context'])) $_REQUEST['context'] = null;
    if(trim($_REQUEST['alias']) != '' && $xingle -> aliasExists($_REQUEST['parent'], $_REQUEST['alias'])){
      exit(
        '<error description="Такой псевдоним в этом разделе уже существует. Выберите другой."/>'
      );
    }
    if(!@domxml_open_mem('<root>'.$_REQUEST['title'].'</root>')){
      $_REQUEST['title'] = htmlspecialchars(
        $_REQUEST['title'],
        ENT_NOQUOTES,
        "UTF-8"
      );
    }
    if(!@domxml_open_mem('<root>'.$_REQUEST['description'].'</root>')){
      $_REQUEST['description'] = htmlspecialchars(
        $_REQUEST['description'],
        ENT_NOQUOTES,
        "UTF-8"
      );
    }
    if(!@domxml_open_mem('<root>'.$_REQUEST['keywords'].'</root>')){
      $_REQUEST['keywords'] = htmlspecialchars(
        $_REQUEST['keywords'],
        ENT_NOQUOTES,
        "UTF-8"
      );
    }
    if($newDocId = $xingle -> createNode($_REQUEST)){
      if(trim($_REQUEST['labels']) != ''){
        $labels -> setDocLabels(
          $newDocId,
          explode(",", trim($_REQUEST['labels']))
        );
      }
      $nodeData = $xingle ->  getNodeInfo($newDocId, $_REQUEST['defaultLang']);
      $visible = (1 + $nodeData['visible'])/2;
      exit(
        '<div class="node" nodeId="'. $nodeData['id'] .'" label="'. $nodeData['label'] .'" unselectable="on"><div class="nodeHead" unselectable="on"><input type="button" class="nodeReverseEmpty" unselectable="on" onclick="switchNode(this.nextSibling)" onfocus="this.blur()" /><span class="nodeTitleHighlighted" id="t'. strtr($nodeData['URL'], '/', '.') .'" title="'. $nodeData['title']. '" unselectable="on" onclick="highlight(this)"><input type="button" class="nodeIconPage" style="-moz-opacity: '. $visible .'; opacity: '. $visible .'; filter:progid:DXImageTransform.Microsoft.Alpha(Opacity='. ($visible*100) .')" unselectable="on" onfocus="this.blur()" />&#xA0;'. $nodeData['title'] .'</span></div><div class="nodeChildren" style="display:none" unselectable="on"><!-- Дочерние узлы, nodeId: '.$newDocId.' --></div></div>'
      );
    } else {
      exit(
        '<error description="Не удалось создать документ: '. htmlspecialchars(var_export($_REQUEST, true), ENT_QUOTES) .'"/>'
      );
    }
  break;
  default:
?>
<html>
<head>
<title>Информация о документе</title>
<script type="text/javascript" charset="windows-1251" src="../scripts/cleanHTML.js"></script>
<script type="text/javascript" src="../scripts/HTTPRequest.js"></script>
<script type="text/javascript" src="../fckeditor/fckeditor.js"></script>
<script type="text/javascript">
var __LOCATION = '<?php echo $_SERVER['SCRIPT_NAME']?>';
var reA = /[^\w-]+/g;
var __REQUEST = new HTTPRequest();

function accept(){
  var dF = document.getElementById('dialogForm');
  if(document.getElementById('title').value == ''){
    alert("Для создания документа нужно задать заголовок");
    document.getElementById('title').focus();
    return false;
  }
//  dF.title.value = typo(dF.title.value);

  if(__REQUEST){
    var path = __LOCATION;
  	var data = "";
  	var nodeId = document.getElementById('id').value;
  	if(nodeId == 0){
  	  path += '?xingle:action=create';
  	} else {
      path += '?xingle:action=update'
  	  data += 'id=' + nodeId + "&";
  	}
    data += 'parent=' + document.getElementById('parent').value + "&";
    data += 'label=' + document.getElementById('label').value + "&";
    data += 'labels=' + encodeURIComponent(document.getElementById('labels').value) + "&";
    data += 'author=' + document.getElementById('author').value + "&";
    data += 'visible=' + (0 + document.getElementById('visible').checked) + "&";
    data += 'defaultLang=' + document.getElementById('defaultLang').value + "&";
    data += 'title=' + encodeURIComponent(document.getElementById('title').value) + "&";
    data += 'alias=' + document.getElementById('alias').value + "&";
    data += 'contentType=' + document.getElementById('contentType').value + "&";
    data += 'templates=' + document.getElementById('template').value + "&";
    data += 'description=' + encodeURIComponent(document.getElementById('description').value) + "&";
    data += 'keywords=' + encodeURIComponent(document.getElementById('keywords').value) + "&";
    data += 'thumbnail=' + encodeURIComponent(document.getElementById('thumbnail').value);

    var result = __REQUEST.post(
      path,
      data,
      {"Content-type": "application/x-www-form-urlencoded"}
    );
//    alert(__REQUEST.request.responseText)

    if(result && result.documentElement && result.documentElement.nodeName != 'error'){
      reloadParent(document.getElementById('alias').value);
      return false;
    }
    try {
      alert(result.documentElement.getAttribute('description'));
    } catch (e) {
      alert("Во время сохранения произошла ошибка:\n" + __REQUEST.request.responseText);
    }
    window.returnValue = false;
  }
  return false;
}

function reloadParent(alias){
  try {
    var opLoc = window.opener.location;
    var lastSlash = opLoc.pathname.substr(-1) == '/'? '' : '/';
    var target = (document.getElementById('id').value == 0)? lastSlash + alias : '';
    opLoc.assign(opLoc.pathname + target);
  } catch(e) {}
  window.close();
  return false;
}

function chooseFile(){
  var param = showModalDialog(
    'webfolder.html',
    document.getElementById('thumbnail').value,
    "dialogWidth:60em; dialogHeight:40em; help: no; status: no"
  );
  if(param) {
    document.getElementById('thumbnail').value = param;
  }
}

function chooseLabels(){
  var param = showModalDialog(
    'labels.htm',
    self,
    "dialogWidth:60em; dialogHeight:30em; help: no; status: no; resizable: yes"
  );
  if(typeof param == 'string') {
    document.getElementById('labels').value = param;
  }
}
</script>
<link rel="STYLESHEET" type="text/css" href="dialog.css">
</head>
<body>
<form name="dialogForm" id="dialogForm" onsubmit="return accept()">
<input type="hidden" name="id" id="id" value="<?php echo $nodeInfo['id'] ?>">
<input type="hidden" name="parent" id="parent" value="<?php echo $nodeInfo['parent'] ?>">
<input type="hidden" name="label" id="label" value="<?php echo $nodeInfo['label'] ?>">
<input type="hidden" name="labels" id="labels" value="<?php echo $nodeInfo['labels'] ?>">
<input type="hidden" name="author" id="author" value="1">
<fieldset>
<legend>Основная информация</legend>
<table align="center" cellspacing="1" cellpadding="2" border="0" width="100%">
<col style="text-align: right; width: 35%" />
<col style="width: 65%" />
<tbody>
<tr>
  <td title="Основной язык документа (по умолчанию)"><label for="defaultLang">Основной язык</label></td>
  <td><?php
    if($nodeInfo['id'] == 0){
?><select name="defaultLang" id="defaultLang"><?php
      foreach ($langs as $langId => $data){
?>
<option value="<?php echo $langId ?>"><?php echo $data['name'], " [", $data['code'], "]" ?></option>
<?php
      }
?></select><?php
    } else {
?>
<input type="hidden" name="defaultLang" id="defaultLang" value="<?php echo $nodeInfo['defaultLang'] ?>" readonly>
<input type="text" value="<?php echo $langs[$nodeInfo['defaultLang']]['name'] ?>" readonly>
<?php
    }
?></td>
</tr>
<tr>
  <td title="Заголовок документа - любые символы"><label for="title">Заголовок</label></td>
  <td><input type="text" name="title" id="title" value="<?php echo htmlspecialchars($nodeInfo['title'], ENT_QUOTES) ?>"></td>
</tr>
<tr>
  <td title="Псевдоним - Латинские буквы (A-Za-z), цифры (0-9), символ почеркивания (_). дефис(-)"><label for="alias">Псевдоним</label></td>
  <td><input type="text" name="alias" id="alias" onblur="if(this.value.match(reA)){this.style.backgroundColor='pink'; this.focus()} else {this.style.backgroundColor=''}" value="<?php
echo $nodeInfo['alias']
?>"<?php
if($nodeInfo['alias'] != '' || $nodeInfo['label'] == 'ROOT') echo " disabled";
?>></td>
</tr>
<tr>
  <td><label for="contentType">Основное содержимое</label></td>
  <td><select name="contentType" id="contentType"<?php if($nodeInfo['id'] > 0) echo " disabled" ?>><?php
foreach($contentTypes as $num => $data){
?>
<option value="<?php echo $num ?>"<?php if($nodeInfo['contentType'] == $num) echo " selected"?>><?php echo $data['title'] ?></option>
<?php
}
?></select></td>
</tr>
<tr>
  <td title="Используется как аннотация в оглавлении"><label for="description">Описание<label></td>
  <td>
    <textarea cols="20" rows="4" name="description" id="description"><?php echo $nodeInfo['description'] ?></textarea>
    <script type="text/javascript">
/*if(window.FCKeditor){
  var dFCKeditor = new FCKeditor('description');
  dFCKeditor.ToolbarSet = "Description";
  dFCKeditor.Height = '160px';
  dFCKeditor.Config.ToolbarStartExpanded = false;
  dFCKeditor.ReplaceTextarea();
}*/
</script>
  </td>
</tr>
<tr>
  <td title="Ключевые слова"><label for="keywords">Ключевые слова</label></td>
  <td><textarea cols="20" rows="4" name="keywords" id="keywords"><?php echo $nodeInfo['keywords'] ?></textarea></td>
</tr>
<tr style="display: none">
  <td title="Иллюстрация к документу"><label for="thumbnail">Иллюстрация</label></td>
  <td><input type="text" style="width: 20em" name="thumbnail" id="thumbnail" value="<?php echo $nodeInfo['thumbnail'] ?>"><input type="button" style="width: 6em" value="Выбрать" onclick="chooseFile()"></td>
</tr>
<tr>
  <td title="Показывать в оглавлениях"><label for="visible">Показывать в&nbsp;оглавлениях</label></td>
  <td><input type="checkbox" class="auto" name="visible" id="visible"<?php if($nodeInfo['visible'] == 1) echo " checked" ?>></td>
</tr>
</tbody></table></fieldset>
<fieldset style="display: none">
<legend>Дополнительно</legend>
<table align="center" cellspacing="1" cellpadding="2" border="0" width="100%">
<col style="text-align: right; width: 35%" />
<col style="width: 65%" />
<tbody>
<tr>
  <td><label for="template">Шаблон страницы</label></td>
  <td><select name="template" id="template">
<option value="0" selected>Наследовать</option>
</select></td>
</tr>
<tr style="disply: none;>
  <td title="Категории"><label for="labelsChoice">Категории</label></td>
  <td><button style="width: auto" id="labelsChoice" onclick="chooseLabels()">Выбрать</button></td>
</tr>
<tr>
  <td title="Дата и время"><label for="dateChoice">Дата и время</label></td>
  <td><button style="width: auto" id="dateChoice" disabled>Изменить</button></td>
</tr>
</tbody>
</table></fieldset>
<div align="center"><button class="btn" type="submit" name="add">ОК</button>
<button class="btn" onclick="window.close()">Отмена</button></div>
</form>
</body>
</html>
<?php
}
?>